<?php
require 'DBMysql.class.php';
/**
 *
 * 主从分离
 * Beck Confidential
 * Copyright (c) 2013, Beck Corp. <Beck.Bi>.
 * All rights reserved.
 *
 * PHP version 5
 *
 * @category  Aug
 * @package package_name
 * @author beck
 * @date 2013-8-10
 * @license
 * @link

 *
 */
class ProxyMysql
{

	public static $instance = null;
	/**
	 * 数据库主库句柄
	 */
	protected $dbMasterHandler;

	/**
	 * 数据库丛库句柄
	 */
	protected $dbSlaveHandler;


	private $_defaultDbName;


	/**
	 *
	 */
	private function __construct()
	{
		$this->dbMasterHandler = false;
		$this->dbSlaveHandler  = false;
		$this->_defaultDbName  = DBConfig::$defaultDBName;
	}

	/**
	 * 获取自己的实例
	 * @return ProxyMysql
	 */
	public static function getInstance()
	{
		if (empty(self::$instance)) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * 获取主库连接
	 * @return boolean
	 */
	public function getMasterDbHandler()
	{
		$this->reconnectMasterDbHandler();
		if($this->dbMasterHandler === false){
			$this->dbMasterHandler = DBMysql::createHandle(DBConfig::$SERVER_MASTER,
							#$this->_defaultDbName,
			                DBConfig::$SERVER_MASTER["database"],
							DBConfig::$SERVER_MASTER["charset"]);
			if (FALSE === $this->dbMasterHandler) {
				SimpleLogger::log(sprintf('MASTERDB TIME=%s FILE=%s LINE=%s MESSAGE=%s', date('Y-m-d H:i:s'), __FILE__, __LINE__, 'master db handler create fail'), LogConfig::ERROR,'mysql');
			}
		}
		return $this->dbMasterHandler;
	}


	/**
	 * 获取从库连接
	 * @return boolean
	 */
	public function getSlaveDbHandler()
	{

		$this->reconnectSlaveDbHandler();
		if($this->dbSlaveHandler === false){
			$this->dbSlaveHandler = DBMysql::createHandle(DBConfig::$SERVER_SLAVE,
							#$this->_defaultDbName,
							#DBEncode::ENCODING_UTF8);
			                DBConfig::$SERVER_MASTER["database"],
			                DBConfig::$SERVER_MASTER["charset"]);
			if (FALSE === $this->dbSlaveHandler) {
				SimpleLogger::log(sprintf('SLAVEDB TIME=%s FILE=%s LINE=%s MESSAGE=%s', date('Y-m-d H:i:s'), __FILE__, __LINE__, 'slave db handler create fail'), LogConfig::ERROR,'mysql');
			}
		}
		return $this->dbSlaveHandler;
	}

	/**
	 * 释放主库连接
	 */
	public function reconnectMasterDbHandler() {
		if ($this->dbMasterHandler && !mysqli_ping($this->dbMasterHandler)) {
			DBMysql::releaseDBHandle($this->dbMasterHandler);
			$this->dbMasterHandler = false;
			SimpleLogger::log('MASTERDB release', LogConfig::INFO, 'mysql');
		}
	}


	/**
	 * 释放从库连接
	 */
	public function reconnectSlaveDbHandler() {
		if ($this->dbSlaveHandler && !mysqli_ping($this->dbSlaveHandler)) {
			DBMysql::releaseDBHandle($this->dbSlaveHandler);
			$this->dbSlaveHandler = false;
			SimpleLogger::log('SLAVEDB release', LogConfig::INFO, 'mysql');
		}
	}


	/**
	 * 设置数据库名称
	 *
	 * @param unknown $dbName
	 */
	public function setDefaultDbName($dbName)
	{
		if (is_string($dbName) && '' != trim($dbName)) {
			$this->_defaultDbName = $dbName;
		}
	}


}